from rest_framework import serializers
from .models import Team, TeamMember, TeamRanking
from apps.users.serializers import UserSerializer

class TeamMemberSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    avatar = serializers.SerializerMethodField()

    class Meta:
        model = TeamMember
        fields = ['id', 'user_id', 'username', 'avatar', 'role']

    def get_avatar(self, obj):
        return f"https://api.dicebear.com/7.x/avataaars/svg?seed={obj.user.username}"

class TeamSerializer(serializers.ModelSerializer):
    creator_name = serializers.CharField(source='creator.username', read_only=True)
    creator_avatar = serializers.SerializerMethodField()
    members = serializers.SerializerMethodField()
    member_count = serializers.SerializerMethodField()

    class Meta:
        model = Team
        fields = [
            'id', 'name', 'description', 'goal', 
            'creator', 'creator_name', 'creator_avatar',
            'start_date', 'end_date', 'max_members', 
            'category', 'level', 'status', 'created_at',
            'members', 'member_count'
        ]

    def get_creator_avatar(self, obj):
        return f"https://api.dicebear.com/7.x/avataaars/svg?seed={obj.creator.username}"

    def get_members(self, obj):
        members = obj.teammember_set.select_related('user').all()
        return TeamMemberSerializer(members, many=True).data

    def get_member_count(self, obj):
        return obj.teammember_set.count()

    def create(self, validated_data):
        validated_data['creator_id'] = self.context['request'].data.get('creator')
        return super().create(validated_data)

class TeamRankingSerializer(serializers.ModelSerializer):
    team_name = serializers.CharField(source='team.name')
    avatar = serializers.SerializerMethodField()

    class Meta:
        model = TeamRanking
        fields = ['team_name', 'score', 'sprint_count', 'total_hours', 'avatar']

    def get_avatar(self, obj):
        return f"https://api.dicebear.com/7.x/initials/svg?seed={obj.team.name}" 